package ee.maoinvest.frontend.controller.command.enterpriseCommands;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ee.maoinvest.backend.model.data.Enterprise;
import ee.maoinvest.backend.services.EnterpriseService;
import ee.maoinvest.backend.services.implementations.EnterpriseServiceImpl;
import ee.maoinvest.frontend.controller.command.Command;
import ee.maoinvest.frontend.controller.formstringdataconverters.enterpriseforms.EditEnterpriseFormConverter;
import ee.maoinvest.frontend.controller.requestprocessors.EnterpriseFormsRequestProcessor;


public class GetEnterpriseByIDCommand implements Command
{
	private int operationResult = 0;
	private final int OPERATION_SUCCESSFUL = 1;
	private final int OPERATION_UNSUCCESSFUL = 0;
	
	private final int EDITABLE_SUBSTATION_ID_PARSE_ERROR_IDENTIFICATOR = -1;
	
	@Override
	public int executeCommand(HttpServletRequest request,
			HttpServletResponse response) 
	{
		EnterpriseFormsRequestProcessor enterpriseFormsRequestProcessor = null;
		EditEnterpriseFormConverter editEnterpriseFormConverter = null;
		Enterprise enterpriseToEdit = null;
		EnterpriseService enterpriseService = null;
		
		enterpriseFormsRequestProcessor = new EnterpriseFormsRequestProcessor();
		
		int editableEnterpriseID = enterpriseFormsRequestProcessor.getEditableEnterpriseID(request);
		if (editableEnterpriseID != EDITABLE_SUBSTATION_ID_PARSE_ERROR_IDENTIFICATOR)
		{
			enterpriseService = new EnterpriseServiceImpl();
			enterpriseToEdit = enterpriseService.getEnterpriseById(editableEnterpriseID);
			
			if (enterpriseToEdit != null)
			{
				editEnterpriseFormConverter = new EditEnterpriseFormConverter();
				editEnterpriseFormConverter.fillWithInitialData(enterpriseToEdit);
				
				request.setAttribute("editEnterpriseFormConverter", editEnterpriseFormConverter);
				HttpSession session = request.getSession();
				session.setAttribute("enterpriseToEdit", enterpriseToEdit);
				operationResult = OPERATION_SUCCESSFUL;
			}
		}
		else
		{
			operationResult = OPERATION_UNSUCCESSFUL;
		}

		return operationResult;
	}
}